#include "AARect.h"
#include "Ray.h"

AARect::AARect(Vector3 c1, Vector3 c2, int axis, Vector3 N)
: m_c1(c2), m_c2(c2)
{
	m_min = Vector3(std::min(c1.x, c2.x), std::min(c1.y, c2.y), std::min(c1.z, c2.z));
	m_max = Vector3(std::max(c1.x, c2.x), std::max(c1.y, c2.y), std::max(c1.z, c2.z));
	m_axis = axis;
	m_norm = N;
}

AARect::~AARect()
{
}

bool AARect::intersect(HitInfo& result, const Ray& ray)
{	
	Vector3 inv_d = Vector3(1/ray.d.x, 1/ray.d.y, 1/ray.d.z);
	float t = (m_min[m_axis] - ray.o[m_axis])*inv_d[m_axis];

	int u = (m_axis + 1) % 3;
	int v = (m_axis + 2) % 3;

	Vector3 p = ray.o + t*ray.d;
	if(t>0. && (p[u] > m_min[u]) && (p[v] > m_min[v]) && (p[u] < m_max[u]) && (p[v] < m_max[v])) {
		result.t = t;
		result.P = p;
		result.N = m_norm;
		return true;
	}

	return false;
}
